# 线性回归的4种方法
# 方法1：原始方法


import numpy as np
import matplotlib.pyplot as plt

# 方法1，构造一元线性回归
def method1(xx, yy):
    m = xx.shape[0]
    xavg = np.mean(xx)
    x2 = np.sum(xx ** 2)

    aa = np.sum(yy * (xx - xavg))
    bb = np.sum(xx) ** 2 / m

    w = aa / (x2 - bb)
    b = np.sum(yy - w * xx) / m
    return w, b


def func(x, w, b):
    return x * w + b


if __name__ == '__main__':
    # print_hi('PyCharm')

    m = 101
    x_train = np.linspace(-1, 1, m)
    x_train = x_train.reshape(-1, 1)
    print(x_train.shape)
    y_train = 2 * x_train + np.random.randn(*x_train.shape) * 0.33

    ###########################方法1
    plt.figure(1)
    plt.scatter(x_train, y_train)

    w, b = method1(x_train, y_train)
    print(w, b)

    xx = np.array([-1, 1]).reshape(-1, 1)
    z = func(xx, w, b)
    plt.plot(xx, z, color='r', linewidth=4.0, linestyle="--")
    # z = func(x_train, w, b)
    # plt.plot(x_train, z, color='r', linewidth=4.0, linestyle="--")

    plt.show()


